package com.leetcode.stack_queue;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author Dennis Li
 * @date 2020/9/4 17:11
 */
public class MaxSlidingWindow {

    static class MonotonicQueue {

        Deque<Integer> queue;

        public MonotonicQueue(Deque<Integer> queue) {
            this.queue = queue;
        }

        public void offer(int num) {
            while (!queue.isEmpty() && num > queue.peekLast()) {
                queue.pollLast();
            }
            queue.offerLast(num);
        }

        public void poll(int num) {
            if (!queue.isEmpty() && num == queue.peekFirst())
                queue.pollFirst();
        }

        public int max() {
            return queue.peekFirst();
        }
    }

    public int[] maxSildingWindow(int[] nums, int k) {
        final MonotonicQueue queue = new MonotonicQueue(new LinkedList<>());
        int len = nums.length;
        int[] res = new int[len - k + 1];
        for (int i = 0; i < len; i++) {
            if (i < k - 1)
                queue.offer(nums[i]);
            else {
                queue.offer(nums[i]);
                res[i - k + 1] = queue.max();
                queue.poll(nums[i - k + 1]);
            }
        }
        return res;
    }

}
